<?php

namespace App\Models;


class AuthGroupAccess extends BaseModel
{
    protected $table = "auth_group_access";

    public $timestamps = false;

    public function __construct()
    {
        parent::__construct();
    }

    public function admin()
    {
        return $this->hasOne('App\Models\Admin', 'id', 'aid');
    }

    public function group()
    {
        return $this->hasOne('App\Models\AuthGroup', 'id', 'group_id');
    }

    public function getAuthAccessAdminList($group_id, $pageSize = 10, $pageLength = 5)
    {
        $fields = 'id,nickname,last_login_time,last_login_ip,status';
        $where['status'] = ['>', 0];
        $order['id'] = 'asc';
        $rows = $this->withCertain('admin', $fields, $where, $order)->multiWhere(['group_id' => $group_id])->paginate($pageSize);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), $pageLength);
        }
        return $rows;
    }

    public function getAdminGroupRulesById($id)
    {
        $res = $this->withCertain('group', 'id,rules')->multiWhere(['aid' => $id])->first();
        if ($res) {
            $res = $res->toArray();
        }
        return $res;
    }

    /**
     * 把管理员添加到权限组,支持批量添加管理员到权限组
     * 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
     */
    public function addToGroup()
    {
        $aids = trim(request('aid'));
        $gid = request('group_id');
        $aids = str_replace('，', ',', $aids);
        if (strpos($aids, ',')) {
            $aids = explode(',', trim($aids, ','));
        }
        if (!($aids && $gid)) {
            $this->error = '参数有误';
            return false;
        }
        if (is_numeric($aids)) {
            if (is_administrator($aids)) {
                $this->error = '该用户为超级管理员';
                return false;
            }
            $admin = new Admin();
            if (!$admin->_getOne(['id' => $aids])) {
                $this->error = '用户不存在';
                return false;
            }
            $aids = [$aids];
        }
        if (!$this->checkAdminId($aids)) {
            return false;
        }
        $this->_start();
        try {
            //为单个权限组批量添加管理员时,先删除旧数据
            $this->_del(['aid' => ['in', $aids]]);
            $data = [];
            foreach ($aids as $v) {
                $data[] = ['aid' => $v, 'group_id' => $gid];
            }
            $this->_add($data);
            $this->_commit();
            return '操作成功！';
        } catch (\Exception $e) {
            $this->_rollBack();
            $this->error = '操作失败！';
            return false;
        }
    }

    public function removeFromGroup()
    {
        $where['aid'] = request('aid');
        $where['group_id'] = request('group_id');
        if ($where['aid'] == session('admin.id')) {
            $this->error = '不允许解除自身授权';
            return false;
        }
        if (count($where) < 2) {
            $this->error = '参数有误';
            return false;
        }
        $group = new AuthGroup();
        $res = $group->_getOne(['id' => $where['group_id']]);
        if (!$res) {
            $this->error = '用户组不存在';
            return false;
        }
        $res = $this->_del($where);
        if (!$res) {
            $this->error = '操作失败';
        }
        return '操作成功';
    }


    /**
     * 检查id是否全部存在
     * @param array|string $gid 管理员id列表
     */
    public function checkAdminId($ids)
    {
        $admin = new Admin();
        $res = $admin->_getList(['id' => ['in', $ids]], 'id');
        if (count($res) === count($ids)) {
            return true;
        } else {
            $res = array_column($res->toArray(), 'id');
            $diff = implode(',', array_diff($ids, $res));
            $this->error = '以下管理员id不存在: ' . $diff;
            return false;
        }
    }
}